import { _decorator, Component, Node, Vec3 } from 'cc';
import { StateDefine } from '../../Config';
import { EnemyState } from '../EnemyState';
import { Enemy_Skeleton } from './Enemy_Skeleton';
const { ccclass, property } = _decorator;

@ccclass('SkeletonBattleState')
export class SkeletonBattleState extends EnemyState {
    moveDir = 0;
    protected enemy: Enemy_Skeleton;
    constructor(name: StateDefine, _enemy: Enemy_Skeleton, anim: StateDefine) {
        super(name, _enemy, anim);
        this.enemy = _enemy;
    }

    onEnter() {
        super.onEnter();
        this.enemy.ZeroVelocity();
        this.stateTime = this.enemy.BattleTime;
    }
    onExit() {
        super.onExit();
    }
    update(deltaTime: number) {
        super.update(deltaTime);
        if (this.enemy.node.getPosition().x < this.enemy.playerNode.getPosition().x) {
            this.moveDir = 1;
        } else {
            this.moveDir = -1;
        }
        const dis = Vec3.distance(this.enemy.node.getWorldPosition(),this.enemy.playerNode.getWorldPosition())

        if(dis<20)
            this.enemy.ZeroVelocity()
        else
            this.enemy.setVelocity(this.moveDir * this.enemy.MoveSpeed, this.rb.linearVelocity.y);
        
        if(this.enemy.IsPlayerDetected()){
            this.stateTime = this.enemy.BattleTime;
            if (this.enemy.IsAttackDetected()) {
                this.enemy.stateMgr.transit(StateDefine.SkeletonAttack);
            }
        }else if(this.stateTime<0 || dis>180){
            this.enemy.stateMgr.transit(StateDefine.SkeletonIdle);
        }
    }
    onDestory() { }

    canTransit(to: StateDefine): boolean {
        if (to == StateDefine.SkeletonAttack && this.enemy.LastAttack + this.enemy.AttackCoolDown > new Date().getTime()) return false;
        return true;
    }
}


